<template>
  <div class="container">
    <div class="input-group">
      <el-input v-model="beginAddress" placeholder="请输入出发站" />
      <img :src="'../../public/切换.png'" @click="exchange()" class="exchange-icon"/>
      <el-input v-model="endAddress" placeholder="请输入目的站" />
    </div>
      <el-date-picker style="margin-top: 15px; margin-bottom: 8px;" clearable
          v-model="beginDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择发车日期">
        </el-date-picker>
    <div class="button-group">
      <el-button style="width: 200px; margin-bottom: 10px;" type="primary" @click="search" class="search-button">查询</el-button>
    </div>
    <el-table :data="ticket" stripe border style="width: 100%; font-size: 14px; color: #333">
    <el-table-column label="序号" type='index' width="55" align="center"/>
    <el-table-column prop="number" label="车次"/>
    <el-table-column prop="nowAddress" label="出发站"  />
    <el-table-column prop="nextAddress" label="终点站" />
    <el-table-column prop="beginTime" label="发车时间" />
    <el-table-column prop="endTime" label="到站时间" />
    <el-table-column prop="remainCount" label="余票" />
    <el-table-column prop="price" label="票价" />
    <el-table-column prop="op" label="操作" >
    <template #default="scope">
      <!-- 购买按钮 -->
      <el-button type="primary" @click="handleBuy(scope.row)">购买</el-button>
    </template>
  </el-table-column>
  </el-table>
  </div>

  
</template>

<script setup>
import { ref, reactive } from 'vue'
import {select,buy} from '../api/select'

const beginAddress=ref('')
const endAddress=ref('')
const beginDate=ref('')
const ticket=ref([])

function exchange() {
    [beginAddress.value, endAddress.value] = [endAddress.value, beginAddress.value]
}
function search(){
  select(beginAddress.value,endAddress.value,beginDate.value).then(res=>{
    ticket.value=res.data;
  }).catch(err => {
      console.log(err)
      alert("查询失败！")
    })
}

function handleBuy(row){
  const data=ref({
    userId: localStorage.getItem("userId"),
    account: localStorage.getItem("userAccount"),
    name: localStorage.getItem("username"),
    number: row.number,
    price: row.price,
    beginTime: row.beginTime,
    endTime: row.endTime,
    nowAddress: row.nowAddress,
    nextAddress: row.nextAddress,
    price: row.price,
    carriageNumber: Math.floor(Math.random() * 20) + 1,
    setNumber: Math.floor(Math.random() * 20) + 1
  })
  buy(data.value).then(res=>{   
    alert("已加入待支付订单")
  }).catch(err => {
      console.log(err)
      alert("购买失败！")
    })
}

</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.input-group {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.exchange-icon {
  height: 40px;
  cursor: pointer;
}

.button-group {
  margin-top: 20px;
}

.search-button {
  width: 100%;
}
</style>